package com.fable.dynamicDataSource.controller;

import com.fable.dynamicDataSource.domain.User;
import com.fable.dynamicDataSource.dynamicDataSource.DynamicDataSourceContextHolder;
import com.fable.dynamicDataSource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String getUserList(@RequestParam("ds") String dataSource, Map<String, Object> model) {
        List<User> users = null;
        if ("ds1".equals(dataSource)) {
            DynamicDataSourceContextHolder.setDataSource("ds1");
            users = userService.findUsersByDatasourcce1();
        } else if ("ds2".equals(dataSource)) {
            DynamicDataSourceContextHolder.setDataSource("ds2");
            users = userService.findUsersByDatasourcce2();
        } else {
            users = userService.findUsersByDefaultDatasourcce();
        }
        model.put("userList", users);
        return "user";
    }

}
